#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os, sys, urllib2, json, socket
from os import path
from urlparse import urlparse
from time import sleep
from httpclient import HttpClient
#from win32pipe import CreateNamedPipe

#http://v.ifeng.com/appData/video/getLiveInfo_iPhone.js
#http://live.3gv.ifeng.com/zixun.m3u8
#User-Agent: Lavf54.17.100

def win32_unicode_argv():
    """Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode
    strings.

    Versions 2.x of Python don't support Unicode in sys.argv on
    Windows, with the underlying Windows API instead replacing multi-byte
    characters with '?'.
    """

    from ctypes import POINTER, byref, cdll, c_int, windll
    from ctypes.wintypes import LPCWSTR, LPWSTR

    GetCommandLineW = cdll.kernel32.GetCommandLineW
    GetCommandLineW.argtypes = []
    GetCommandLineW.restype = LPCWSTR

    CommandLineToArgvW = windll.shell32.CommandLineToArgvW
    CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)]
    CommandLineToArgvW.restype = POINTER(LPWSTR)

    cmd = GetCommandLineW()
    argc = c_int(0)
    argv = CommandLineToArgvW(cmd, byref(argc))
    if argc.value > 0:
        # Remove Python executable and commands if present
        start = argc.value - len(sys.argv)
        return [argv[i] for i in
                xrange(start, argc.value)]

class MyClient(HttpClient):
    def __init__(self):
        super(MyClient,self).__init__();
    def _request(self, url, data= None, **hdrs):
        headers = {"User-Agent":"Lavf54.17.100",
                   "Accept-Encoding": "gzip, deflate",
                   "Connection": "keep-alive"
                   }
        headers.update(hdrs)
        self.req = self.request(url,headers= headers, data= data)
        self.url = url
        return self.req
    def on_response(self,resp):
        pass
        #con = resp.getheader('Connection')
        #print('{}:{}'.format(self.url,con))

client = MyClient()

def retrieve(url, agent):
    global client
    try:
        req = client._request(url, **{'User-Agent':agent})
        data = client.open(req).data
    except (socket.timeout,socket.error, IOError ):
        client = MyClient()
    return data

def write_pipe(data):
    from ctypes import POINTER, byref, cdll, c_int, windll, c_int
    kernel32 = windll.kernel32
    global pipe
    szread = c_int()
    kernel32.WriteFile(pipe,data,len(data),byref(szread),None)
    data

def down(url,path):
    f = open(path,'ab')
    print("Getting "+url)
    data = retrieve(url, 'Lavf54.17.100')
    #write_pipe(data)
    f.write(data)
    f.flush()
    f.close()
    
def ts_stream(url):
    bname = path.basename(url);
    bname = 'e:\\video\\' + bname + '.mp4'
    if os.path.isfile(bname):
        os.remove(bname)
    haves = []
    while True:
        data = retrieve(url, 'Lavf54.17.100')
        data = data.splitlines()
        streams = [a for a in data if a[0] != '#']
        for stream in streams:
            if stream in haves: continue
            haves.append(stream)
            down("{}://{}/".format(*urlparse(url))+stream, bname)
        if len(haves) > 10:
            del haves[0]
        sleep(6)

def create_pipe():
    from ctypes import POINTER, byref, cdll, c_int, windll, c_int
    kernel32 = windll.kernel32
    global pipe
    pipe = kernel32.CreateNamedPipeA(r'\\.\pipe\aaaa.ts',0x02|0x00080000,0x00,1,0x10000,0x10000,0,None)
    ret = kernel32.ConnectNamedPipe(pipe,None)
    #pmod = c_int(0x1)
    #ret = kernel32.SetNamedPipeHandleState(pipe,byref(pmod),None,None)

def ts_multi_streawm(url):
    data = retrieve(url, 'Lavf54.17.100')
    data = data.splitlines()
    streams = [a for a in data if a[0] != '#']
    ts_stream("{}://{}/".format(*urlparse(url))+streams[0])

def main(argv):
    #create_pipe()
    data = retrieve("http://v.ifeng.com/appData/video/getLiveInfo_iPhone.js", 'Dalvik/1.6.0 (Linux; U; Android 4.3; Google 4.3 Base Build/JLS36G)')
    jdic = json.loads(data)
    target = min([a['video'] for a in jdic['liveInfo'] if a['name'].find(argv[0]) >= 0 ])
    ts_multi_streawm(target)

if __name__ == '__main__':
    sys.argv = win32_unicode_argv()
    sys.exit(main(sys.argv[1:]))
